package com.java.upload.service.impl;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.java.upload.service.UploadService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author jl
 * @description
 * @date 2019-10-15 11:38
 */
@Service
public class UploadServiceImpl implements UploadService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadServiceImpl.class);

    private static final List<String> CONTENT_TYPE = Arrays.asList("image/jpeg","image/gif","image/png","application/x-png");

    @Autowired
    private FastFileStorageClient storageClient;

    @Override
    public String uploadImage(MultipartFile file) {
        //校验文件类型
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        if (!CONTENT_TYPE.contains(contentType)){
            LOGGER.info("文件类型不合法:{}",originalFilename);
            return null;
        }

        try {
            //校验文件内容
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null) {
                LOGGER.info("文件内容不合法:{}",originalFilename);
                return null;
            }
            //保存 D:\Download
            //file.transferTo(new File("D:\\Download\\"+originalFilename));

            //保存到fastDFS
            String ext = StringUtils.substringAfterLast(originalFilename,".");
            StorePath path = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
            //返回url,进行回显
            //return "http://image.leyou.com/"+originalFilename;
            return "http://image.leyou.com/:8000"+path.getFullPath();
        } catch (IOException e) {
            LOGGER.info("服务器内部错误:{}",originalFilename);
            e.printStackTrace();
        }
        return null;
    }
}
